package text00.tx06;

import java.util.Arrays;

public class MyArrayList<Z> {
    private static final int DEFAULT_CAPACITY = 10;
    private Object[] elements;
    private int size;
    public MyArrayList() {
        elements = new Object[DEFAULT_CAPACITY];
        size = 0;
    }

    public MyArrayList(int capacity) {
        elements = new Object[capacity];
    }

    // 动态扩容
    private Object[] grow(Object[] elementData) {
        int newCapacity = elementData.length * 2;
        Z[] newArray = (Z[]) new Object[newCapacity];
        System01<Z> system01 = new System01<>();
        system01.arraycopy((Z[]) elementData, 0, newArray, 0, elementData.length);
        return newArray;
    }

    // 添加元素
    public void add(Z element) {
        if (size == elements.length) {
            elements = grow(elements);
        }
        elements[size++] = element;
    }

    // 删除元素
    public Z remove(int index) {
        Z element = (Z) elements[index]; // 记录要删除的元素

        // 把后面的元素往前移动
        for (int i = index; i < size - 1; i++) {
            elements[i] = elements[i + 1];
        }

        elements[size - 1] = null; // 清空最后一个元素，防止内存泄漏
        size--; // 更新大小

        return element;
    }

    // 返回集合元素的实际个数
    public int size() {
        return size;
    }

    // 给集合某个下标设置元素
    public Z set(int index, Z element) {
        elements[index] = element;
        return element;
    }

    // 获取集合下标对应的元素
    public Z get(int index) {
        return (Z) elements[index];
    }

    // 判断集合是否为空
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public String toString() {
        return Arrays.toString(Arrays.copyOf(elements, size)); // 只返回有效元素
    }
}
